// stores/userStore.ts
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import {UserModel} from "@/shared/services/model/user";

interface UserState {
  userInfo: UserModel | null
  setUserInfo: (userInfo: UserModel) => void
  clearUserInfo: () => void
}

const miniProgramStorage = {
  getItem: (name: string): string | null => {
    try {
      return wx.getStorageSync(name)
    } catch (error) {
      return null
    }
  },
  setItem: (name: string, value: string): void => {
    try {
      wx.setStorageSync(name, value)
    } catch (error) {
      console.error('保存存储失败:', error)
    }
  },
  removeItem: (name: string): void => {
    try {
      wx.removeStorageSync(name)
    } catch (error) {
      console.error('删除存储失败:', error)
    }
  },
}

export const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      userInfo: null,
      setUserInfo: (userInfo: UserModel) => {
        set({ userInfo })
      },
      clearUserInfo: () => {
        set({ userInfo: null })
      }
    }),
    {
      name: 'user-storage',
      storage: createJSONStorage(() => miniProgramStorage),
    }
  )
)
